package main

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	//	/"net/url"
	"os"
	"strconv"

	//	_ "github.com/go-sql-driver/mysql"
	//	"github.com/jmoiron/sqlx"
)

type docTBytes struct {
	Type int
	Data io.ReadCloser
}

func redirectPolicyFunc(req *http.Request, via []*http.Request) error {
	//req.Header.Add("Authorization", "Basic "+basicAuth("username1", "password123"))
	cfg := LoadCfg()
	req.SetBasicAuth(cfg.RRDUserName, cfg.RRDPassword)
	return nil
}

func downdoc(loanId int, name string, doctype int) {

	fmt.Println("a. 读取配置文件")
	cfg := LoadCfg()

	fmt.Println("b. 读取loan")
	loan := FetchLoan(loanId)

	fmt.Println("c. 读取bondoffer")
	boffer := FetchBondOfferByWithdraw(loan.WithdrawId)

	switch boffer.MajorDepoProductId {
	case 2:
		var filename bytes.Buffer
		filename.WriteString(strconv.Itoa(loanId))
		filename.WriteString("_")
		filename.WriteString(getFundSys(boffer.MajorDepoProductId))
		filename.WriteString("_")
		filename.WriteString(getDocType(2))
		filename.WriteString("_")
		filename.WriteString(name)
		filename.WriteString(".pdf")
		//		proxy := func(_ *http.Request) (*url.URL, error) {
		//			return url.Parse("http://127.0.0.1:8888")
		//		}

		client := &http.Client{
			CheckRedirect: redirectPolicyFunc,
		}
		//client.Transport = &http.Transport{Proxy: proxy}
		req, err := http.NewRequest("GET", cfg.RRDUrl+cfg.RRDLendContract+strconv.Itoa(loanId), nil)
		req.SetBasicAuth(cfg.RRDUserName, cfg.RRDPassword)
		resp, err := client.Do(req)

		fullname := ""
		switch doctype {
		case 1:
			fullname = "./纠纷账户/" + filename.String()
		case 2:
			fullname = "./失联账户/" + filename.String()
		case 3:
			fullname = "./未接通名单/" + filename.String()
		}

		output, err := os.Create(fullname)
		if err != nil {
			fmt.Println("Error while creating", filename, "-", err)
			return
		}
		defer output.Close()

		n, err := io.Copy(output, resp.Body)
		if err != nil {
			fmt.Println("Error while downloading", filename, "-", err)
			return
		}

		fmt.Println(n, "bytes downloaded.")

		//case 3:
		//		docs := FetchLoanDocuments(loan.WithdrawId)

		//		for _, doc := range docs {
		//			if doc.DocumentType != 0 {

		//				var filename bytes.Buffer
		//				filename.WriteString(strconv.Itoa(loanId))
		//				filename.WriteString("_")
		//				filename.WriteString(getFundSys(boffer.MajorDepoProductId))
		//				filename.WriteString("_")
		//				filename.WriteString(getDocType(doc.DocumentType))
		//				filename.WriteString("_")
		//				filename.WriteString(name)
		//				filename.WriteString(".pdf")

		//				client := &http.Client{}
		//				req, err := http.NewRequest("GET", cfg.S3Url, nil)
		//				req.SetBasicAuth(cfg.S3UserName, cfg.S3Password)
		//				resp, err := client.Do(req)

		//				fullname := ""
		//				switch doctype {
		//				case 1:
		//					fullname = "./纠纷账户/" + filename.String()
		//				case 2:
		//					fullname = "./失联账户/" + filename.String()
		//				case 3:
		//					fullname = "./未接通名单/" + filename.String()
		//				}

		//				output, err := os.Create(fullname)
		//				if err != nil {
		//					fmt.Println("Error while creating", filename, "-", err)
		//					return
		//				}
		//				defer output.Close()

		//				n, err := io.Copy(output, resp.Body)
		//				if err != nil {
		//					fmt.Println("Error while downloading", filename, "-", err)
		//					return
		//				}

		//				fmt.Println(n, "bytes downloaded.")

		//			}
		//
		//}
	}
}

func getFundSys(sysId int) string {
	switch sysId {
	case 1:
		return "易源俏特殊资金"
	case 2:
		return "人人贷"
	case 3:
		return "Viking"
	case 4:
		return "VikingHistory"
	case 5:
		return "HeiKa"
	}
	return ""
}

func getDocType(doctype int) string {
	switch doctype {
	case 1044001:
		return "借款协议"
	case 1044002:
		return "信用服务协议"
	case 1044003:
		return "授权扣款委托书"
	case 1044004:
		return "身份证明"
	case 1044005:
		return "贷款申请表"
	case 1044006:
		return "查询授权书"
	case 1044007:
		return "信用咨询及管理服务协议"
	case 1044008:
		return "借款协议（补）"
	case 1044009:
		return "信用报告"
	case 1044010:
		return "客户审核流程表"
	case 1044011:
		return "学历证明"
	case 1044012:
		return "工作证明"
	case 1044013:
		return "劳动合同"
	case 1044014:
		return "补充资料"
	case 1044015:
		return "其他"
	}
	return ""
}

func main() {
	os.Mkdir("纠纷账户", os.ModePerm)
	os.Mkdir("失联账户", os.ModePerm)
	os.Mkdir("未接通名单", os.ModePerm)

	//downdoc(500017, "wef", 2)

	tmpdata := LoadInData()

	fmt.Println("##############开始下载【纠纷账户】##############")
	for _, el := range tmpdata.Type1 {
		fmt.Println("处理loan：" + strconv.Itoa(el.LoanId))
		downdoc(el.LoanId, el.Name, 1)
	}

	fmt.Println("##############开始下载【失联账户】##############")
	for _, el := range tmpdata.Type2 {
		fmt.Println("处理 loan：" + strconv.Itoa(el.LoanId))
		downdoc(el.LoanId, el.Name, 2)
	}

	fmt.Println("##############开始下载【未接通名单】##############")
	for _, el := range tmpdata.Type3 {
		fmt.Println("处理 loan：" + strconv.Itoa(el.LoanId))
		downdoc(el.LoanId, el.Name, 3)
	}
	fmt.Println("##############执行完成##############")
}
